<?php
class ModelTotalSample extends Model {
  public function getTotal(&$total_data, &$total, &$taxes) {
    $this->load->language('total/sample');
    $this->load->model('account/customer');
    $customer_info = $this->model_account_customer->getCustomer($this->customer->getId());
    if(isset($customer_info['sample_bill_amount'])&&$customer_info['sample_bill_used']==0&&$customer_info['sample_bill_amount']!=0) {
      //判断用户名下是否有首次拿样订单
      if ($this->hasSampleOrder()) {
        return;
      }
      // $sample_amount = (float)$customer_info['sample_bill_amount'];
      // if ($sample_amount > $total) {
      //   $sample_delta = $total;
      // } else {
      //   $sample_delta = $sample_amount;
      // }

      $sample_delta = 0;
      if ($total>5000) {
        $sample_delta = 300;
      } else if ($total>3000) {
        $sample_delta = 100;
      }

      if ($sample_delta > 0) {
        $total_data[] = array(
          'code'       => 'sample',
          'title'      => $this->language->get('text_sample'),
          'value'      => -$sample_delta,
          'sort_order' => $this->config->get('sample_sort_order')
        );

        $total -= $sample_delta;
      }
    }
  }

  public function hasSampleOrder() {
    $query = M("order_total ot")
    ->join("`order` o on o.order_id=ot.order_id")
    ->where("o.order_status_id!=0 and ot.code='sample' and o.customer_id = '" .$this->customer->getId(). "'")->select();
    if (empty($query)) {
      return false;
    }
    require true;
  }

  public function confirm($order_info, $order_total) {
    $this->load->language('total/sample');

    if ($order_info['customer_id']) {
      $query = M('customer')
      ->data(array('sample_bill_used'=>1))
      ->where(array('customer_id'=>(int)$order_info['customer_id']))
      ->save();
    }
  }

  public function unconfirm($order_id) {
    $this->load->model('account/order');

    $order_info = $this->model_account_order->getOrder($order_id);
    if ($order_info&&$order_info['customer_id']) {
      $query = M('customer')
      ->data(array('sample_bill_used'=>0))
      ->where(array('customer_id'=>(int)$order_info['customer_id']))
      ->save();
    }
  }
}